/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.server.timerTask;


import cn.ac.iie.di.wx.server.common.RuntimeEnv;
import cn.ac.iie.di.wx.server.utils.RedisUtil;
import cn.ac.iie.di.wx.server.vo.RedisVo;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Austin
 */
public class RetryTask implements Runnable {

    static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RetryTask.class.getName());
    public RedisUtil redisUtil;
    public LinkedBlockingQueue<RedisVo> retryQueue;

    public RetryTask(RedisUtil redisUtil, LinkedBlockingQueue<RedisVo> retryQueue) {
    }

    @Override
    public void run() {
        logger.info("RetryTask start");
        try {
            while (true) {
                logger.info("RetryTask run");
                Thread.sleep(300000);
                int size = RuntimeEnv.retryQueue.size();
                if (size == 0) {
                    continue;
                }
                logger.info("retry size is: " + size);
                for (int i = 0; i < size; ++i) {
                    //logger.info("try "+i);
                    RedisVo vo = RuntimeEnv.retryQueue.poll(500, TimeUnit.MILLISECONDS);
                    if (vo == null) {
                        break;
                    } else {
                        String okflag = redisUtil.set(vo.getKey(), vo.getValue());
                        if (okflag.equals("OK")) {
                            logger.info("set into redis:" + vo.getKey());
                        } else {
                            RuntimeEnv.retryQueue.put(vo);
                            logger.info("set redis "+okflag+",will retry");
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("RetryTask class error : " + e, e);
        }

    }

    public LinkedBlockingQueue<RedisVo> getRetryQueue() {
        return retryQueue;
    }

    public void setRetryQueue(LinkedBlockingQueue<RedisVo> retryQueue) {
        this.retryQueue = retryQueue;
    }

    public RetryTask(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

}
